package com.agrimall.servlet.merchant;

import com.agrimall.entity.Product;
import com.agrimall.entity.User;
import com.agrimall.service.ProductService;
import com.agrimall.service.impl.ProductServiceImpl;
import com.agrimall.util.FileUploadUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

/**
 * 商户商品管理Servlet
 */
@WebServlet("/merchant/product")
public class ProductManageServlet extends HttpServlet {
    private ProductService productService = new ProductServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User merchant = (User) session.getAttribute("merchant");
        
        if (merchant == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
            // 商品列表
            String pageStr = request.getParameter("page");
            String keyword = request.getParameter("keyword");
            String category = request.getParameter("category");
            
            int page = 1;
            if (pageStr != null && !pageStr.isEmpty()) {
                try {
                    page = Integer.parseInt(pageStr);
                } catch (NumberFormatException e) {
                    page = 1;
                }
            }
            int pageSize = 10;
            
            List<Product> products;
            int totalCount = 0;
            
            try {
                // 判断查询条件
                boolean hasKeyword = keyword != null && !keyword.trim().isEmpty();
                boolean hasCategory = category != null && !category.trim().isEmpty();
                
                if (hasKeyword && hasCategory) {
                    // 同时有名称和分类
                    products = productService.searchProductsByMerchantNameAndCategory(merchant.getUserId(), keyword.trim(), category.trim(), page, pageSize);
                    totalCount = productService.countProductsByMerchantNameAndCategory(merchant.getUserId(), keyword.trim(), category.trim());
                } else if (hasKeyword) {
                    // 只有名称
                    products = productService.searchProductsByMerchantAndName(merchant.getUserId(), keyword.trim(), page, pageSize);
                    totalCount = productService.countProductsByMerchantAndName(merchant.getUserId(), keyword.trim());
                } else if (hasCategory) {
                    // 只有分类
                    products = productService.getProductListByMerchantAndCategory(merchant.getUserId(), category.trim(), page, pageSize);
                    totalCount = productService.countProductsByMerchantAndCategory(merchant.getUserId(), category.trim());
                } else {
                    // 都没有，查询全部
                    products = productService.getProductListByMerchantExcludeDeleted(merchant.getUserId(), page, pageSize);
                    totalCount = productService.countProductsByMerchantExcludeDeleted(merchant.getUserId());
                }
                
                // 确保products不为null
                if (products == null) {
                    products = new java.util.ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
                products = new java.util.ArrayList<>();
                request.setAttribute("error", "查询商品失败：" + e.getMessage());
            }
            
            int totalPages = totalCount > 0 ? (int) Math.ceil((double) totalCount / pageSize) : 1;
            
            request.setAttribute("products", products);
            request.setAttribute("page", page);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("totalCount", totalCount);
            request.setAttribute("keyword", keyword);
            request.setAttribute("category", category);
            request.getRequestDispatcher("/merchant/product/list.jsp").forward(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User merchant = (User) session.getAttribute("merchant");
        
        if (merchant == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        
        String action = request.getParameter("action");
        
        // 检查是否为multipart请求（文件上传）
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        List<FileItem> items = null;
        
        if (isMultipart) {
            // 如果是multipart请求，先解析获取action和其他参数
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(5 * 1024 * 1024); // 单张图片最大5MB
                items = upload.parseRequest(request);
                
                // 从multipart请求中获取action参数
                if (action == null) {
                    for (FileItem item : items) {
                        if (item.isFormField() && "action".equals(item.getFieldName())) {
                            action = item.getString("UTF-8");
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.print("{\"success\":false,\"message\":\"请求解析失败：" + e.getMessage() + "\"}");
                out.flush();
                out.close();
                return;
            }
        }
        
        if ("addAjax".equals(action) || "updateAjax".equals(action)) {
            // AJAX方式添加或更新商品（支持文件上传）
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            
            try {
                String productIdStr = null;
                String productName = null;
                String category = null;
                String description = null;
                String priceStr = null;
                String stockStr = null;
                String imageUrl = null;
                String statusStr = null;
                
                if (isMultipart && items != null) {
                    // 处理文件上传（商品图片只上传一张）
                    try {
                        String uploadedImageUrl = FileUploadUtil.uploadImages(items, request, 1);
                        if (uploadedImageUrl != null && !uploadedImageUrl.trim().isEmpty()) {
                            imageUrl = uploadedImageUrl.trim();
                        }
                    } catch (Exception e) {
                        out.print("{\"success\":false,\"message\":\"图片上传失败：" + e.getMessage() + "\"}");
                        return;
                    }
                    
                    // 从multipart请求中获取其他参数
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            String fieldName = item.getFieldName();
                            String fieldValue = item.getString("UTF-8");
                            
                            switch (fieldName) {
                                case "action":
                                    // action已经获取，跳过
                                    break;
                                case "productId":
                                    productIdStr = fieldValue;
                                    break;
                                case "productName":
                                    productName = fieldValue;
                                    break;
                                case "category":
                                    category = fieldValue;
                                    break;
                                case "description":
                                    description = fieldValue;
                                    break;
                                case "price":
                                    priceStr = fieldValue;
                                    break;
                                case "stock":
                                    stockStr = fieldValue;
                                    break;
                                case "imageUrl":
                                    // 如果上传了新图片，使用新图片；否则使用原有图片URL
                                    if (imageUrl == null || imageUrl.isEmpty()) {
                                        imageUrl = fieldValue;
                                    }
                                    break;
                                case "status":
                                    statusStr = fieldValue;
                                    break;
                            }
                        }
                    }
                } else {
                    // 普通表单提交
                    productIdStr = request.getParameter("productId");
                    productName = request.getParameter("productName");
                    category = request.getParameter("category");
                    description = request.getParameter("description");
                    priceStr = request.getParameter("price");
                    stockStr = request.getParameter("stock");
                    imageUrl = request.getParameter("imageUrl");
                    statusStr = request.getParameter("status");
                }
                
                // 收集验证错误信息
                java.util.List<String> errors = new java.util.ArrayList<>();
                
                // 验证商品名称
                if (productName == null || productName.trim().isEmpty()) {
                    errors.add("商品名称");
                }
                
                // 验证价格
                BigDecimal price = null;
                if (priceStr == null || priceStr.trim().isEmpty()) {
                    errors.add("商品价格");
                } else {
                    try {
                        price = new BigDecimal(priceStr.trim());
                        if (price.compareTo(BigDecimal.ZERO) < 0) {
                            errors.add("商品价格（必须大于等于0）");
                        }
                    } catch (NumberFormatException e) {
                        errors.add("商品价格（格式不正确）");
                    }
                }
                
                // 验证库存
                Integer stock = null;
                if (stockStr == null || stockStr.trim().isEmpty()) {
                    errors.add("库存数量");
                } else {
                    try {
                        stock = Integer.parseInt(stockStr.trim());
                        if (stock < 0) {
                            errors.add("库存数量（必须大于等于0）");
                        }
                    } catch (NumberFormatException e) {
                        errors.add("库存数量（格式不正确）");
                    }
                }
                
                // 修改商品时，图片必须不为空
                if ("updateAjax".equals(action)) {
                    Product existingProduct = null;
                    if (productIdStr != null && !productIdStr.trim().isEmpty()) {
                        try {
                            existingProduct = productService.getProductById(Long.parseLong(productIdStr));
                        } catch (NumberFormatException e) {
                            errors.add("商品ID（格式不正确）");
                        }
                    }
                    
                    if (existingProduct != null) {
                        // 验证商品是否属于当前商户
                        if (!existingProduct.getMerchantId().equals(merchant.getUserId())) {
                            out.print("{\"success\":false,\"message\":\"无权操作该商品\"}");
                            return;
                        }
                        
                        // 检查图片：如果没有上传新图片，且原有商品也没有图片，则报错
                        boolean hasNewImage = (imageUrl != null && !imageUrl.trim().isEmpty());
                        boolean hasOldImage = (existingProduct.getImageUrl() != null && !existingProduct.getImageUrl().trim().isEmpty());
                        
                        if (!hasNewImage && !hasOldImage) {
                            errors.add("商品图片（修改商品时图片不能为空）");
                        } else if (!hasNewImage && hasOldImage) {
                            // 如果没有上传新图片，使用原有图片
                            imageUrl = existingProduct.getImageUrl();
                        }
                    } else if (productIdStr == null || productIdStr.trim().isEmpty()) {
                        errors.add("商品ID");
                    }
                }
                
                // 如果有验证错误，返回错误信息
                if (!errors.isEmpty()) {
                    out.print("{\"success\":false,\"message\":\"请检查以下字段：" + String.join("、", errors) + "\"}");
                    return;
                }
                
                Product product = new Product();
                
                if ("updateAjax".equals(action) && productIdStr != null && !productIdStr.trim().isEmpty()) {
                    // 更新商品
                    product.setProductId(Long.parseLong(productIdStr));
                } else {
                    // 新增商品
                    product.setMerchantId(merchant.getUserId());
                }
                
                product.setProductName(productName.trim());
                if (category != null && !category.trim().isEmpty()) {
                    product.setCategory(category.trim());
                }
                if (description != null) {
                    product.setDescription(description.trim());
                }
                product.setPrice(price);
                product.setStock(stock);
                
                if (imageUrl != null && !imageUrl.trim().isEmpty()) {
                    product.setImageUrl(imageUrl.trim());
                }
                
                if (statusStr != null && !statusStr.trim().isEmpty()) {
                    product.setStatus(Integer.parseInt(statusStr.trim()));
                } else if ("addAjax".equals(action)) {
                    product.setStatus(1); // 默认上架
                }
                
                boolean success;
                if ("updateAjax".equals(action)) {
                    success = productService.updateProduct(product);
                } else {
                    success = productService.addProduct(product);
                }
                
            if (success) {
                    out.print("{\"success\":true,\"message\":\"" + ("updateAjax".equals(action) ? "更新" : "添加") + "成功\"}");
            } else {
                    // 如果保存失败，删除已上传的图片
                    if (imageUrl != null && !imageUrl.trim().isEmpty() && "addAjax".equals(action)) {
                        FileUploadUtil.deleteFiles(request, imageUrl);
                    }
                    out.print("{\"success\":false,\"message\":\"" + ("updateAjax".equals(action) ? "更新" : "添加") + "失败，请重试\"}");
                }
            } catch (NumberFormatException e) {
                out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
            } catch (Exception e) {
                e.printStackTrace();
                out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
            } finally {
                out.flush();
                out.close();
            }
        } else if ("deleteAjax".equals(action)) {
            // 逻辑删除商品
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            
            try {
                String productIdStr = request.getParameter("productId");
                if (productIdStr == null || productIdStr.trim().isEmpty()) {
                    out.print("{\"success\":false,\"message\":\"参数不完整\"}");
                    return;
                }
                
                Long productId = Long.parseLong(productIdStr);
                
                // 验证商品是否属于当前商户
                Product product = productService.getProductById(productId);
                if (product == null || !product.getMerchantId().equals(merchant.getUserId())) {
                    out.print("{\"success\":false,\"message\":\"无权操作该商品\"}");
                    return;
                }
                
                boolean success = productService.logicalDeleteProduct(productId);
                if (success) {
                    out.print("{\"success\":true,\"message\":\"删除成功\"}");
                } else {
                    out.print("{\"success\":false,\"message\":\"删除失败，请重试\"}");
                }
            } catch (NumberFormatException e) {
                out.print("{\"success\":false,\"message\":\"参数格式错误\"}");
            } catch (Exception e) {
                e.printStackTrace();
                out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
            } finally {
                out.flush();
                out.close();
            }
        } else if ("batchDelete".equals(action)) {
            // 批量删除商品
            batchDeleteProducts(request, response, merchant);
        }
    }
    
    /**
     * 批量删除商品
     */
    private void batchDeleteProducts(HttpServletRequest request, HttpServletResponse response, User merchant)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String[] productIdStrs = request.getParameterValues("productIds[]");
            
            if (productIdStrs == null || productIdStrs.length == 0) {
                out.print("{\"success\":false,\"message\":\"请选择要删除的商品\"}");
                return;
            }
            
            List<Long> productIds = new java.util.ArrayList<>();
            for (String productIdStr : productIdStrs) {
                try {
                    Long productId = Long.parseLong(productIdStr.trim());
                    productIds.add(productId);
                } catch (NumberFormatException e) {
                    // 忽略无效的ID
                }
            }
            
            if (productIds.isEmpty()) {
                out.print("{\"success\":false,\"message\":\"没有有效的商品ID\"}");
                return;
            }
            
            int successCount = 0;
            int failCount = 0;
            
            for (Long productId : productIds) {
                try {
                    // 验证商品是否属于当前商户
                    Product product = productService.getProductById(productId);
                    if (product == null || !product.getMerchantId().equals(merchant.getUserId())) {
                        failCount++;
                        continue;
                    }
                    
                    // 逻辑删除商品
                    boolean success = productService.logicalDeleteProduct(productId);
                    if (success) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                }
            }
            
            if (failCount == 0) {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个商品\"}");
            } else {
                out.print("{\"success\":true,\"message\":\"成功删除 " + successCount + " 个商品，失败 " + failCount + " 个\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"服务器错误：" + e.getMessage() + "\"}");
        } finally {
            out.flush();
            out.close();
        }
    }
}
